package fileutils

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"go/build"
	"io/fs"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func FindRootPkg() string {
	return FindBeanGofileUtil().FindRootPkg()
}

func SetRootPkgEnv(p string) {
	FindBeanGofileUtil().SetRootPkgEnv(p)
}

func CheckConfigFileExist(root, f string) bool {
	return FindBeanGofileUtil().TryFileExist(root + f)
}

func FindRootDir() string {
	return FindBeanGofileUtil().FindRootDir()
}

func FindRootDirGoMod() string {
	return FindBeanGofileUtil().FindRootDirGoMod()

}

func FindDirs(rootdir string) ([]string, error) {
	var result []string = make([]string, 0)
	// 指定需要遍历的目录
	var rd, err = os.ReadDir(rootdir)

	for _, r := range rd {
		if r.IsDir() {
			result = append(result, r.Name())
		}
	}
	// 返回nil继续遍历

	if err != nil {
		logrus.Error("Error walking the path:", err)
	}
	return result, err
}

func FindAllDirs(dirPath string) ([]string, error) {
	var result []string = make([]string, 0)

	// 使用filepath.Walk遍历目录
	err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			logrus.Error(err)
			return err
		}
		// 如果是文件，可以进行额外操作，比如读取文件内容
		if info.IsDir() {

			result = append(result, path)
		}
		// 返回nil继续遍历
		return nil
	})

	if err != nil {
		logrus.Error("Error walking the path:", err)
	}
	return result, err
}
func GetCurPath() string {
	return FindBeanGofileUtil().GetCurPath()
}

func CheckFileExist(filename string) bool {

	return FindBeanGofileUtil().CheckFileExist(filename)

}
func TryFileExist(filename string) bool {

	return FindBeanGofileUtil().TryFileExist(filename)

}
func UnZip(zipFile string, destPath string) error {
	return FindBeanGofileUtil().UnZip(zipFile, destPath)
}

func Zip(srcPath string, destFile string) error {
	return FindBeanGofileUtil().Zip(srcPath, destFile)
}
func Dir(pathfile string) string {
	return FindBeanGofileUtil().Dir(pathfile)
}
func ReadSubDirs(rootPath string) ([]string, error) {
	var dirs = []string{}
	entries, err := os.ReadDir(rootPath)
	if err != nil {
		return dirs, err
	}

	for _, entry := range entries {
		_, err := entry.Info()
		if err != nil {
			// 可能是权限问题或其他错误
			fmt.Println("Error getting info for", entry.Name(), ":", err)
			continue
		}
		dirs = append(dirs, entry.Name())

	}
	return dirs, nil
}
func WriteBytesFile(filename string, bytes []byte) error {

	return ioutil.WriteFile(filename, bytes, fs.ModePerm)

}
func FileNameOfPath(pathfile string) string {

	names := strings.Split(pathfile, "/")

	var l = len(names)
	logrus.Info(names, names[l-1])
	return names[l-1]
}

func ReadFileToString(file string) (string, error) {
	var b, err = ioutil.ReadFile(file)
	return string(b), err

}

func ImportPkg(pkgpath string) (*build.Package, error) {
	return build.Default.Import(pkgpath, "", build.FindOnly)

}
func ImportPkgDir(pkgpath string) (string, error) {
	var p, e = build.Default.Import(pkgpath, "", build.FindOnly)
	if e != nil {
		return p.Dir, e
	}
	return "", e

}
